<?php

/**
 * goodsCategory actions.
 *
 * @package    WacStorehouse
 * @subpackage goodsCategory
 * @author     Ben
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class goodsCategoryActions extends WacCommonActions {

    /**
     * Executes an application defined process prior to execution of this sfAction object.
     *
     * By default, this method is empty.
     */
    public function preExecute() {
//      $this->moduleName = sfContext::getInstance()->getRequest()->getParameter("module");
//      $moduleName = $this->moduleName;
//      $this->mainModuleTable = Doctrine::getTable(WacTable::$$moduleName);

      parent::preExecute();
    }

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */

    public function executeIndex(sfWebRequest $request) {
        //    $this->forward('default', 'module');
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->hasParameter('parent'));
        if ($request->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $output = '';
        $resultSet = JsCommonData::getCommonDatum();
        $errorFlag = false;

        // check duplicated codes
        if(Doctrine::getTable(WacTable::$goodsCategory)->isExistedCode($request->getParameter("code"))) {
            $resultSet['info'] = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName), WacErrorCode::$duplicatedName);
            $errorFlag = true;
        }

        if(!$errorFlag) {
            if($request->getParameter("id")=="-1")  // create new node
            {
                $parentNode = Doctrine::getTable(WacTable::$goodsCategory)->findOneById($request->getParameter("parent"));

                $selfLayer = $parentNode->getSelfLayer()+1;
                $theNode = Doctrine::getTable(WacTable::$goodsCategory)->create();
                $theNode->setParent($parentNode->getId());
                $theNode->setSelfLayer($selfLayer);
                $theNode->setName($request->getParameter("name"));
                $theNode->setCode($request->getParameter("code"));
                $theNode->setNodeType(WacTreeType::$leaf);

                for($i=1; $i<$selfLayer && $i<=Doctrine::getTable(WacTable::$goodsCategory)->maxLayerNum; $i++) {
                    $setMethod = "setLayer{$i}";
                    $getMethod = "getLayer{$i}";
                    $theNode->$setMethod($parentNode->$getMethod());
                }
                $setMethod = "setLayer{$selfLayer}";
                $theNode->save();

                if($selfLayer<= Doctrine::getTable(WacTable::$goodsCategory)->maxLayerNum ) {
                    $theNode->$setMethod($theNode->getId());
                }

                $theNode->save();

                if($parentNode->getNodeType()==0) {
                    $parentNode->setNodeType(WacTreeType::$branch);
                    $parentNode->save();
                }

                $this->afterAdd($request, $theNode);

            }

            //        $resultSet["items"] = $request->getParameterHolder()->getAll();
            $resultSet["items"] = JsTreeDataHelper::getInstance()->getJsTreeNode($theNode->toArray());
            $resultSet['info']  = JsCommonData::getSuccessDatum();
        }

        if ($request->isXmlHttpRequest()) {
            $this->getResponse()->setContentType('application/json; charset=utf-8');
            $output = json_encode($resultSet);
        } else {
            $output = print_r($resultSet, true);
        }

        return $this->renderText($output);
    }

    public function executeModify(sfWebRequest $request) {
        $this->forward404Unless($request->hasParameter('id'));
        if ($request->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = JsCommonData::getCommonDatum();

        try {

            if(Doctrine::getTable(WacTable::$goodsCategory)->isExistedCode($request->getParameter("code"),$request->getParameter("id"))) {
                $errorMsg = WacErrorCode::getInfo(WacErrorCode::$duplicatedName);
                throw new WacAppException($errorMsg, WacErrorCode::$duplicatedName);
            }
            
            $theNode = Doctrine::getTable(WacTable::$goodsCategory)->findOneById($request->getParameter("id"));

            if($request->getParameter("code")!=$theNode->getCode() && in_array($theNode->getCode(), WacGoodsCategory::$predefinedClassCodes))
            {
                $errorMsg = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_predefined_class_edit");
                throw new WacAppException($errorMsg, WacErrorCode::$logicError);
            }

            $theNode->setName($request->getParameter("name"));
            $theNode->setCode($request->getParameter("code"));
            $theNode->save();

            $this->afterEdit($request);

            //        $resultSet["items"] = $request->getParameterHolder()->getAll();
            $resultSet["items"] = JsTreeDataHelper::getInstance()->getJsTreeNode($theNode->toArray());
            $resultSet['info']  = JsCommonData::getSuccessDatum();

        }
        catch (WacAppException $e) {		// catch application exception, and handle it
            $resultSet['info'] = JsCommonData::getErrorDatum($e->getMessage(), $e->getCode());
        }
        catch (Exception $e) {        // catch general exception
            WacAppException::handleGeneralError($e);
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

    public function executeDelete(sfWebRequest $request) {
        $this->forward404Unless($request->hasParameter('id'));
        if ($request->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }
        
        $resultSet = JsCommonData::getCommonDatum();

        try {
            $theNode = Doctrine::getTable(WacTable::$goodsCategory)->findOneById($request->getParameter("id"));
            $parentNode = Doctrine::getTable(WacTable::$goodsCategory)->findOneById($request->getParameter("parent"));

            if(in_array($theNode->getCode(), WacGoodsCategory::$predefinedClassCodes))
            {
                $errorMsg = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_predefined_class_delete");
                throw new WacAppException($errorMsg, WacErrorCode::$logicError);
            }

            if($theNode->isBranch()) {
                Doctrine::getTable(WacTable::$goodsCategory)->delTree($theNode->getId(),$theNode->getSelfLayer());
            }
            else {
                Doctrine::getTable(WacTable::$goodsCategory)->delete($theNode->getId());
            }

            if(!$parentNode->hasChildren()) {
                $parentNode->setNodeType(WacTreeType::$leaf);
                $parentNode->save();
            }

            $this->afterDelete($request);


            //        $resultSet["items"] = $request->getParameterHolder()->getAll();
            $resultSet["items"] = JsTreeDataHelper::getInstance()->getJsTreeNode($parentNode->toArray());
            $resultSet['info']  = JsCommonData::getSuccessDatum();

        }
        catch (WacAppException $e) {		// catch application exception, and handle it
            $resultSet['info'] = JsCommonData::getErrorDatum($e->getMessage(), $e->getCode());
        }
        catch (Exception $e) {        // catch general exception
            WacAppException::handleGeneralError($e);
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

    public function executeDeep(sfWebRequest $request) {
        $this->forward404Unless($request->hasParameter('id'));
        if ($request->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $output = '';
        $resultSet = JsCommonData::getCommonDatum();

        $theNode = Doctrine::getTable(WacTable::$goodsCategory)->findOneById($request->getParameter("id"));


        //        $resultSet["items"] = $request->getParameterHolder()->getAll();
//        $resultSet["items"] = JsTreeDataHelper::getInstance()->getJsTreeNode($parentNode->toArray());
        $resultSet['info']  = "deep is: ".JsTreeDataHelper::getInstance()->getDepth($request->getParameter("id"), WacTable::$goodsCategory, 500);


        if ($request->isXmlHttpRequest()) {
            $this->getResponse()->setContentType('application/json; charset=utf-8');
            $output = json_encode($resultSet);
        } else {
            $output = print_r($resultSet, true);
        }

        return $this->renderText($output);

    }

    /*
   * @return hash list data array
   */
  protected function getHashList($keyField, $valField, $page=1, $rows=20, $condStr="")
  {
      $resultSet = array();
      $arrParam = array();
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }
      $arrParam['orderBy'] = "t1.parent asc, t1.name asc";

      $request = $this->getRequest();
      if($request->hasParameter("q") && $request->getParameter("q")!=""){
          $arrParam['andWhere'][] = "t1.name like '%".$request->getParameter("q")."%'";
      }

      if($request->hasParameter("parent") && $request->getParameter("q")!=""){
          $objGoodsCategory = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", $request->getParameter("parent"));
          $arrParam['andWhere'][] = "t1.parent = '".$objGoodsCategory->getId()."'";
      }

      if($condStr!="")
      {
          $arrParam['andWhere'][] = $condStr;
      }

      $listItems = $this->mainModuleTable->getCustomList($arrParam, $page, $rows, true);

      if(count($listItems)>0)
      {
          foreach($listItems as $listItem)
          {
              $tmpArr = array();
//              $keyMethodName = "get".ucfirst($keyField);
//              $valueMethodName = "get".ucfirst($valField);
//              $tmpArr[$arrListItem->$keyMethodName()] = $arrListItem->$valueMethodName();
              $tmpArr = array("key"=>$listItem[$keyField], "value"=>$listItem[$valField]);
              $resultSet[] = $tmpArr;
          }
      }

      return $resultSet;
  }

  /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetIdNameHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();

        $items = $this->getHashList("id", "name", 1, sfConfig::get("maxHashItems"));
        switch($request->getParameter("data_format")) {
            case StaticWacDataFormatType::$jsonFlexbox:
                $resultSet = JqFlexboxDataHelper::getInstance()->getCommonDatum($items);
                break;
            default:
                break;
        }
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

  /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetProductHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();
        
        $objGoodsCategory1 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classWeaveCode"]);
        $objGoodsCategory2 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classCleanUpCode"]);

        $ids = array($objGoodsCategory1->getId(), $objGoodsCategory2->getId());
        $items = $this->mainModuleTable->getIdNameHashListByParents($ids, 500, "t1.parent asc, t1.name asc");
        
        $resultSet = OutputHelper::getInstance()->datumFormat($items, $request);
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

  /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetCottonHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();

        $objGoodsCategory1 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classCottonCode"]);

        $ids = array($objGoodsCategory1->getId());
        $items = $this->mainModuleTable->getIdNameHashListByParents($ids, 500, "t1.parent asc, t1.name asc");

        $resultSet = OutputHelper::getInstance()->datumFormat($items, $request);
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

    /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetDyeHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();

        $objGoodsCategory1 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classDyeCode"]);

        $ids = array($objGoodsCategory1->getId());
        $items = $this->mainModuleTable->getIdNameHashListByParents($ids, 500, "t1.parent asc, t1.name asc");

        $resultSet = OutputHelper::getInstance()->datumFormat($items, $request);
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

     /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetWeaveHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();

        $objGoodsCategory1 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classWeaveCode"]);

        $ids = array($objGoodsCategory1->getId());
        $items = $this->mainModuleTable->getIdNameHashListByParents($ids, 500, "t1.parent asc, t1.name asc");

        $resultSet = OutputHelper::getInstance()->datumFormat($items, $request);
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

      /*
   *  apply different dataFormater according to request params "data_format"
   *  return id=>name hash as select html format
   */
    public function executeGetCleanUpHashInFormat(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = array();

        $objGoodsCategory1 = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("Code", WacGoodsCategory::$predefinedClassCodes["classCleanUpCode"]);

        $ids = array($objGoodsCategory1->getId());
        $items = $this->mainModuleTable->getIdNameHashListByParents($ids, 500, "t1.parent asc, t1.name asc");

        $resultSet = OutputHelper::getInstance()->datumFormat($items, $request);
        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }

}

